package com.fudan.es.aggs.entity;

import java.util.LinkedList;
import java.util.List;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.Aggregation;

public class AggsList {

	private List<AggsPack> aggsList;
	private AggsList() {
		aggsList = new LinkedList<>();
	}
	public <A extends Aggregation> A getAggsResponse(SearchResponse resp) {
		Object obj = null;
		try {
			for (AggsPack aggsPack : aggsList) {
				if (obj == null) {
					obj = aggsPack.getAggs(resp);
				}else {
					obj = aggsPack.getAggs(obj);
				}
			}
			return (A)obj;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static AggsList build() {
		return new AggsList();
	}
	public AggsList addAggs(String name) {
		this.aggsList.add(AggsPack.build(name));
		return this;
	}
	public AggsList addAggs(String...names) {
		for (String name : names) {
			this.aggsList.add(AggsPack.build(name));
		}
		return this;
	}
	public AggsList addAggs(AggsList aggList) {
		this.aggsList.addAll(aggList.getAggsList());
		return this;
	}
	public List<AggsPack> getAggsList() {
		return aggsList;
	}
	public void setAggsList(List<AggsPack> aggsList) {
		this.aggsList = aggsList;
	}

}
